/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package data;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 * @author bertram
 */
public class GoogleSearch {

    public static void artistSearch(String searchTerm) {
    }

    public GoogleSearch() {
    }

    public ArrayList<Integer> workSearch(String searchTerm) {

       ArrayList<Integer> results = new ArrayList<Integer>();
       /*  results.add(375372);
        results.add(365488);*/
        
        try {
            String searchString = URLEncoder.encode(searchTerm, "UTF-8");
            URL url = new URL("https://www.googleapis.com/customsearch/"
                    + "v1?key=AIzaSyBdX91jq8197wfwqD0Xg_2mEQo314g-Lfw&cx="
                    + "017302376099750063030:p-ac5ycijiy&q="
                    + searchString
                    + "&alt=json");
            URLConnection connection = url.openConnection();
            //connection.addRequestProperty("Referer", "http://billeddeling.dk");
            String line;
            StringBuilder builder = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }

            JSONObject json = new JSONObject(builder.toString());
            JSONArray jarr = json.getJSONArray("items");
            System.out.println("længde: " + jarr.length());
            for (int i = 0; i < jarr.length(); i++) {
                JSONObject jo = jarr.getJSONObject(i);
                System.out.println("link: " + jo.getString("link") + "\n");
                String vaerkID = jo.getString("link").split("vaerkId=")[1];
                int vaerk = Integer.parseInt(vaerkID);
                System.out.println("vaerkID: " + vaerk + "\n");
                results.add(vaerk);

            }



        } catch (Exception ex) {
            System.out.println("failure" + ex.getMessage());
            results.add(375372);
            results.add(365488);
            return results;
        }
        return results;
    }
}
